<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/14
 * Time: 16:11
 */
namespace backend\services;
use backend\components\String;
use backend\models\Baseorders;
use backend\models\Baseproducts;
use yii;

class YinheService
{

    /**
     * 订单成功生成后进行银河支付行为
     */
    public function orderPayYinhe($orderId, $payStatus, $openId)
    {
        //统一下单
        $data = Baseorders::find()->where(['OrderId' => $orderId])->asArray()->one();
        $outTradeNo = $orderId;     //商品订单号
        $payAmount = $data['Amount'];//付款金额，单位:0.01元
        $orderName = Baseproducts::findOne(['ProductId'=>$data['ProductId']])->ProductName;    //订单标题
        $notifyUrl = yii::$app->params['notifyUrl'];     //付款成功后的回调地址
        $payTime = time();      //付款时间

        //判断是否使用测试页面的手动输入商户号
        $api_code = yii::$app->params['yinhe_config']['api_code'];
        $api_key = yii::$app->params['yinhe_config']['api_key'];

        $return_url = yii::$app->params['yinhereturnUrl'];//支付成功，用户会跳转到这个地址
        $notify_url = yii::$app->params['yinhenotifyUrl'];;//通知异步回调接收地址

        if (empty($payStatus)){//银河api微信H5支付
            $is_type = 'wechat';
            $url = self::yinhePay($api_code,$api_key,$is_type,$payAmount,$outTradeNo,$orderName,$payTime,$return_url,$notify_url);
            return ['statusCode'=>200, 'message'=>$url];
        }else{
            if ($payStatus == 1){//银河api支付宝H5支付
                $is_type = 'alipay';
                $url = self::yinhePay($api_code,$api_key,$is_type,$payAmount,$outTradeNo,$orderName,$payTime,$return_url,$notify_url);
                return ['statusCode'=>200, 'message'=>$url];
            }elseif ($payStatus == 2){//苹果内购
                return ['statusCode'=>200, 'message'=>'', 'OrderId'=>$outTradeNo, 'UserId'=>$data['UserId']];
            }elseif ($payStatus == 3){//微信APP支付
                $JsApiParame = PayService::createBizPackage($openId,$payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime,$payStatus);
                return ['statusCode'=>200, 'message'=>$JsApiParame];
            }elseif ($payStatus == 4){//微信公众号支付
                $JsApiParame = PayService::createBizPackage($openId,$payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime,$payStatus);
                return ['statusCode'=>200, 'message'=>$JsApiParame];
            }elseif ($payStatus == 5){
                //小程序支付
            }
        }
    }


    public static function yinhePay($api_code,$api_key,$is_type,$payAmount,$orderId,$orderName,$payTime,$return_url,$notify_url)
    {
        $signdata = [
            'return_type' => 'data',		//用户订单编号ID
            'api_code' => $api_code,			//此处填写商户的id
            'is_type' => $is_type,				//支付渠道
            'price' => $payAmount,					//支付金额
            'order_id' => $orderId,			//订单号
            'time' => $payTime,					//支付时间
            'mark' => $orderName,					//此处填写产品名称，或充值，消费说明
            'return_url' => $return_url,		//支付成功，用户会跳转到这个地址
            'notify_url' => $notify_url,		//通知异步回调接收地址
        ];

        $returndata = [
            'return_type' => 'data',		//用户订单编号ID
            'api_code' => $api_code,			//此处填写商户的id
            'is_type' => $is_type,				//支付渠道
            'price' => $payAmount,					//支付金额
            'order_id' => $orderId,			//订单号
            'time' => $payTime,					//支付时间
            'mark' => $orderName,					//此处填写产品名称，或充值，消费说明
            'return_url' => $return_url,		//支付成功，用户会跳转到这个地址
            'notify_url' => $notify_url,		//通知异步回调接收地址
            'sign' => self::make_sign($signdata,$api_key),	//base.php里签名md5加密
        ];
        return self::json_return("OK", $returndata, 1);
    }


    public static function getYinheNotify($json_arr)
    {
        $paysapi_id = $json_arr["paysapi_id"]; 	//服务器API接口返回的唯一支付编码ID
        $order_id = $json_arr["order_id"];			//用户订单编号ID
        $is_type = $json_arr["is_type"];				//支付类型
        $price = $json_arr["price"];				//订单金额
        $real_price = $json_arr["real_price"];		//实际支付金额
        $mark = $json_arr["mark"];					//此处填写产品名称，或充值，消费说明
        $code = $json_arr["code"];					//订单状态
        $sign = $json_arr["sign"];					//服务器API接口返回的唯一key

        //请检查传入的参数是否格式正确
        $api_code = yii::$app->params['yinhe_config']['api_code'];
        $api_key = yii::$app->params['yinhe_config']['api_key'];

        $signdata = array(
            'api_code' => $api_code,			//商户的id;
            'paysapi_id' => $paysapi_id,		//服务器API接口返回的唯一支付编码ID
            'order_id' => $order_id,			//用户订单编号ID
            'is_type' => $is_type,				//支付类型
            'price' => $price,					//订单金额
            'real_price' => $real_price,		//实际支付金额
            'mark' => $mark,					//此处填写产品名称，或充值，消费说明
            'code' => $code						//订单状态
        );
        $temp_sign = self::make_sign($signdata,$api_key);
        return ['sign' => $sign, 'temp_sign' => $temp_sign, 'out_trade_no' => $order_id];
    }



    /**银河支付
     * 生成签名
     * $signdata 签名数据 array
     * $api_key 商户秘钥
     * @return 返回md5签名
     */
    public static function make_sign($signdata,$api_key)
    {
        //签名步骤一：按字典序排序参数
        ksort($signdata);
        $string = self::to_params($signdata);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=".$api_key;
        //$file = "make_sign1";
        //$path ="/data/wwwroot/";
        //$content = $string;
        //F($file,$content,$path);
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 格式化参数格式化成url参数
     */
    public static function to_params($signdata)
    {
        $buff = "";
        foreach ($signdata as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }


    /**
     * 返回json
     * $message 提示文字
     * $data 返回数据 array
     * $code 返回代码
     * @return json字符串
     */
    public static function json_return($message = '',$data = '',$code = 0)
    {
        $return['msg']  = $message;
        $return['data'] = $data;
        $return['code'] = $code;
        return $return;
    }

    /**
     * 写文件
     * $name 文件名
     * $content 写入内容
     * $name 文件路径
     */
    function F($name,$data='',$dir = ''){
        $exc = '.log';

        if (!file_exists($dir)){
            mkdir ($dir,0777,true);
        }
        if(!is_writable($dir.$name.$exc)){
            fopen($dir.$name.$exc, "wd");
        }
        if($data){
            $data = json_encode($data);
            file_put_contents($dir.$name.$exc,date("Y-m-d H:i:s").' '.$data."\r\n", FILE_APPEND);
        }else{
            $data = file_get_contents($dir.$name.$exc);
            $data = str_replace("\r\n","|",$data);
            $data = explode('|',$data);
            $array =  array();
            foreach ($data as $v){
                $array[] = json_decode($v,true);
            }
            return array_filter($array);
        }
    }
    /**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     */

    function curlPost($url, $param)
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $ch=curl_init();
        $timeout=5;
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER, 0);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        $data=curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    /**
     * 模拟JSON提交
     * $url 路径
     * $param_string 数据
     */
    function curlPostJson($url, $param_string){
        $param_string = json_encode($param_string);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param_string);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                "Content-Length: " . strlen($param_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }
}